<?php

namespace frontendx\controllers;

/**
 * @author  shuang
 * @date    2016-10-27 10:39:13
 * @version V1.0
 * @desc    
 */
use common\components\WXController;
use frontendx\models\WB_Task;
use common\components\OperateEvent;
use Yii;
use yii\helpers\Url;
use yii\helpers\Json;
use frontendx\models\WB_UserTaskOperate;
use yii\helpers\ArrayHelper;

class TaskController extends WXController {

    public $message = "";
    public $flag = false;
    public $operateid;

    /*
     * 任务列表(任务大厅)
     */

    public function actionWork() {
        $this->headerTitle = "开始任务";
        $this->headerReflash = true;
        $event = new OperateEvent();
        $this->on("reflash_list", [$event, "reflashTasklist"]);
        $this->trigger("reflash_list", $event);
        $this->off("reflash_list");
        $type = Yii::$app->request->get("type", -1);
        $sort = Yii::$app->request->get("sort", "asc") == "asc" ? "desc" : "asc";
        $sortfield = Yii::$app->request->get("sortfield", "price");
        $typeDict = \common\components\MTools::dictDropdown("task_type", true);
        $topData = WB_Task::getTopTask();
        $page = Yii::$app->request->post("page");
        $result = WB_Task::getTaskList($type, $page,100, $sort, $sortfield);
        return $this->render("work", ["data"=>$result,"type" => $type, "topData" => $topData["topdata"], "typeDict" => $typeDict, 'sort' => $sort, 'sortfield' => $sortfield]);
    }

    public function actionAjaxwork() {
        $this->layout = false;
        $page = Yii::$app->request->post("page");
        $type = Yii::$app->request->post("type");
        $result = WB_Task::getTaskList($type, $page);
        return $this->render("ajaxwork", ["data" => $result]);
    }

    /*
     * 做过的任务
     */

    public function actionMywork() {
        $this->headerTitle = "我做过的全部任务";
        $event = new OperateEvent();
        $this->on("mywork_list", [$event, "myOperateList"]);
        $this->trigger("mywork_list", $event);
        $this->off("mywork_list");
        return $this->render("mywork");
    }

    public function actionAjaxmywork() {
        $this->layout = false;
        $res = \frontendm\models\WB_UserTaskOperate::getOperateTaskList(1);
        return $this->render("ajaxmywork", ["data" => $res["data"]]);
    }

    /*
     * 进行中任务（接了任务尚未完成）
     */

    public function actionMynowork() {
        $this->headerTitle = "我的任务";
        $this->headerReflash = true;
        $event = new OperateEvent();
        $this->on("mywork_list", [$event, "myOperateList"]);
        $this->trigger("mywork_list", $event);
        $this->off("mywork_list");
        $result = \frontendx\models\WB_UserTaskOperate::getOperateTaskList();
        return $this->render("mynowork", $result);
    }

    public function actionAjaxmynowork() {
        $this->layout = false;
        $result = \frontendm\models\WB_UserTaskOperate::getOperateTaskList();
        return $this->render("ajaxmynowork", $result);
    }

    /*
     * 被投诉任务
     */

    public function actionTousu() {
        $this->headerTitle = "被投诉的任务";
        $res = WB_UserTaskOperate::getComplainTaskList();
        return $this->render("tousu", $res);
    }

    public function actionAjaxtousu() {
        $this->layout = false;
        $res = WB_UserTaskOperate::getComplainTaskList();
        return $this->render("ajaxtousu", $res);
    }

    public function actionValidatetask() {
        $this->layout = false;
        if (Yii::$app->request->isAjax) {
            $taskid = Yii::$app->request->get("taskid");
            $tasknum = Yii::$app->request->get("tasknum");
            $event = new OperateEvent(["taskid" => $taskid, "userid" => Yii::$app->user->id]);
            $this->on("open_task", [$event, "openTask"], ["operateMsg" => "开始任务", "tasknum" => $tasknum]);
            $this->trigger("open_task", $event);
            $this->off("open_task");
            if ($this->flag) {
                echo Json::encode(["status" => $this->flag, "msg" => $this->message, "url" => Url::toRoute(["taskdetail", "taskid" => $taskid, "id" => $this->operateid])]);
            } else {
                echo Json::encode(["status" => $this->flag, "msg" => $this->message]);
            }
        }
    }

    public function actionTaskdetail() {
        if (Yii::$app->request->isAjax) {
            $cache_task_image = explode(",", Yii::$app->request->post("images"));
            $operid = Yii::$app->request->post("id");
            $taskaccount = Yii::$app->request->post("taskaccount");
            $OperateEvent = new OperateEvent();
            $content = $OperateEvent->completeTasks($cache_task_image, $operid,$taskaccount);
            echo Json::encode(["status" => $content !== "提交任务失败" ? true : false, "msg" => $content, "url" => Url::toRoute(["work"])]);
            exit;
        } else {
            $this->headerTitle = "任务详情";
            $this->footerShow = false;
            $id = Yii::$app->request->get("id");
            $taskid = Yii::$app->request->get("taskid");
            $model = WB_UserTaskOperate::findOne($id);
            if ($model && $model->status == 0) {
                $res = WB_Task::findOne($taskid);
                $typeModel = \frontendm\models\WB_Dictionary::findOne($res->type);
                $typename = $typeModel->name;
                $areaType = Json::decode($typeModel->description);
                $taskcount = WB_UserTaskOperate::getcompletecount($taskid);
                $jssdk_config = Yii::$app->wechat->jsApiConfig();
                return $this->render("taskdetail", ["taskcount"=>$taskcount,"model" => $model, "taskmodel" => $res, "typename" => $typename,"areaType"=>$areaType, 'jssdk_config' => $jssdk_config]);
            } else {
                throw new \yii\web\NotFoundHttpException("对不起，您要查看的任务已经完成或未按时间完成已退回系统！");
            }
        }
    }

    public function actionTaskdetail2() {
        $this->headerTitle = "任务详情";
        $this->headerReflash = true;
        $this->footerShow = false;
        $taskid = Yii::$app->request->get("taskid");
        $query = new \yii\db\Query();
        $query->from(WB_Task::tableName() . " as a");
        $query->leftJoin(\frontendx\models\WB_TaskPrice::tableName() . " as b", "a.task_price_id=b.id");
        $query->leftJoin("(select count(id) taskcount,taskid from " . \frontendx\models\WB_UserTaskOperate::tableName() . " group by taskid) as c", "a.id=c.taskid");
        $query->select("a.id,a.title,a.created_at,a.step,a.sample_figure,a.type,a.note,a.step_01,a.step_02,a.step_03,a.considerations,a.number,a.areaname,a.vote_address,a.single_meet,a.is_speed,b.brush_price,c.taskcount");
        $query->andWhere("a.id=$taskid");
        $res = $query->one();
        $typeModel = \frontendm\models\WB_Dictionary::findOne($res['type']);
        $areaType = Json::decode($typeModel->description);
        $typename = $typeModel->name;
        $jssdk_config = Yii::$app->wechat->jsApiConfig();
        return $this->render("taskdetail2", ["taskmodel" => $res, "typename" => $typename,"areaType"=>$areaType, 'jssdk_config' => $jssdk_config]);
    }

    public function actionHidetask() {
        $this->layout = false;
        if (Yii::$app->request->isAjax) {
            $id = Yii::$app->request->post("id");
            $action = Yii::$app->request->post("action");
            if ($action === "hide") {
                $event = new OperateEvent(["userid" => Yii::$app->user->id]);
                $this->on("hide_task", [$event, "hideTask"], ["operateMsg" => "隐藏任务", "operateid" => $id]);
                $this->trigger("hide_task", $event);
                $this->off("hide_task");
                echo Json::encode(["status" => $this->flag, "msg" => $this->message, "url" => Url::toRoute(["work"])]);
            } else if ($action === "report") {
                $event = new OperateEvent(["userid" => Yii::$app->user->id]);
                $this->on("report_task", [$event, "reportTask"], ["operateMsg" => "报告任务过期", "operateid" => $id]);
                $this->trigger("report_task", $event);
                $this->off("report_task");
                echo Json::encode(["status" => $this->flag, "msg" => $this->message, "url" => Url::toRoute(["work"])]);
            } else {
                
            }
        }
    }

    public function actionAppeal() {
        $id = Yii::$app->request->get("id");
        $data = WB_UserTaskOperate::find()->with(["taskID"])->where("id=$id")->asArray()->one();
        if (Yii::$app->request->isPost) {
            $event = new OperateEvent(["userid" => Yii::$app->user->id]);
            $this->on("appeal_task", [$event, "appealTask"], ["operateMsg" => "申诉任务", "operateid" => $id]);
            $this->trigger("appeal_task", $event);
            $this->off("appeal_task");
            if ($this->flag) {
                $this->redirect(["tousu"]);
            } else {
                echo '<script>alert("' . $this->message . '");$("#btnSubmit").removeAttr("disabled");</script>';
            }
//            echo Json::encode(["status" => $this->flag, "msg" => $this->message, "url" => Url::toRoute(["mywork"])]);
//            exit;
        }
        return $this->render("appeal", ["data" => $data]);
    }

    public function actionCenter() {
        $amount = \frontendm\models\WB_UserAccountHy::find()->where("userid=" . Yii::$app->user->id)->one();
        if (!$amount instanceof \frontendm\models\WB_UserAccountHy) {
            $amount = 0;
        } else {
            $amount = $amount->amount;
        }
        return $this->render("center", ["amount" => $amount]);
    }

    public function actionAjaxcrontab() {
        $event = new OperateEvent();
        $this->on("reflash_list", [$event, "reflashTasklist"]);
        $this->trigger("reflash_list", $event);
        $this->off("reflash_list");
        $this->on("mywork_list", [$event, "myOperateList"]);
        $this->trigger("mywork_list", $event);
        $this->off("mywork_list");
    }

}
